<template>
  <PageMain>
    <template #header></template>
    <template #body>
      <div
        class="resource-view-1-box w-full h-full overflow-hidden box-border flex justify-start items-center flex-col"
      >
        <div
          class="content w-full h-[calc(100%_-_64px)] box-border p-[20px_24px] overflow-hidden overflow-y-auto"
        >
          <div
            class="w-full h-[56px] p-[16px_0] overflow-hidden box-border flex justify-start items-start"
            style="font-size: 16px; font-weight: bold; color: #394d73"
          >
            <span>基础信息</span>
          </div>
          <div class="info w-full h-auto p-[20px] rounded-[8px]">
            <a-form
              layout="inline"
              :model="handlerData"
              :rules="Rules"
              class="ckd-inner-form-box"
              label-align="left"
              ref="RefFormBox"
            >
              <a-row justify="space-between" class="w-full">
                <a-form-item label="凭证名称" field="credential_code">
                  <TextInput
                    placeholder="请输入项目预算"
                    v-model="handlerData.credential_code"
                  ></TextInput>
                </a-form-item>
              </a-row>
              <a-row justify="space-between" class="w-full">
                <a-form-item label="凭证编号" field="credential_name">
                  <TextInput
                    disabled
                    placeholder="请输入凭证编号"
                    v-model="handlerData.credential_name"
                  ></TextInput>
                </a-form-item>
              </a-row>
            </a-form>
          </div>
          <div
            class="w-full h-[56px] p-[16px_0] overflow-hidden box-border items-start make-plane"
            style="font-family: Microsoft YaHei; font-size: 16px; font-weight: bold; color: #394d73"
          >
            <span>财务数据</span>
          </div>
          <div
            class="table-box w-full overflow-y-auto overflow-hidden box-border flex flex-col"
            ref="RefTableBox"
          >
            <CommonTable
              :showPagination="false"
              :columnsData="addTableData"
              :tableData="tableData"
              :loading="loading"
              @row-click="tableRowClick"
            >
              <template #index="{ rowIndex }">
                <span>{{ rowIndex + 1 }}</span>
              </template>
              <template #summary="{ rowIndex }">
                <TextInput
                  width="100%"
                  :disabled="tableData[rowIndex].isSave"
                  v-model="tableData[rowIndex].summary"
                ></TextInput>
              </template>
              <template #accounting_subject_code="{ rowIndex }">
                <TextInput
                  width="100%"
                  disabled
                  v-model="tableData[rowIndex].accounting_subject_code"
                ></TextInput>
              </template>
              <template #accounting_subject="{ record, rowIndex }">
                <selectInput
                  placeholder="请选择会计科目"
                  width="100%"
                  :disabled="tableData[rowIndex].isSave"
                  @change="accountingSubjectChange(record)"
                  v-model="tableData[rowIndex].accounting_subject"
                >
                  <a-option
                    v-for="item in AccountingSubjectArr"
                    :key="item.code"
                    :value="item.subject"
                  >
                    {{ item.subject }}
                  </a-option>
                </selectInput>
              </template>
              <template #accounting_subject_detail="{ rowIndex }">
                <selectInput
                  class="w-full"
                  width="100%"
                  :disabled="tableData[rowIndex].isSave"
                  placeholder="请选择会计科目"
                  v-model="tableData[rowIndex].accounting_subject_detail"
                >
                  <a-option
                    v-for="item in AccountingSubjectDetailArr"
                    :key="item.code"
                    :value="item.detail"
                    >{{ item.detail }}</a-option
                  >
                </selectInput>
              </template>
              <template #amount="{ rowIndex }">
                <TextInput
                  width="100%"
                  :disabled="tableData[rowIndex].isSave"
                  v-model="tableData[rowIndex].amount"
                ></TextInput>
              </template>
              <template #operator="{ record, rowIndex }">
                <a-link type="primary" v-if="record.isSave" @click="editClick(record, rowIndex)"
                  >编辑</a-link
                >
                <a-link type="primary" v-else @click="saveClick(record)">保存</a-link>
                <a-link type="primary" @click="deleteAsset(record, rowIndex)">删除</a-link>
              </template>
            </CommonTable>
          </div>
          <a-button class="w-full mt-[20px] add-button-box" @click="addRow">
            新增成本分摊项
          </a-button>
        </div>
        <div class="foot-class flex items-center justify-between">
          <div class="mr-10">
            <a-space>
              <a-button @click="callBack">取消</a-button>
              <a-button type="primary" @click="onCompleteClick">更新</a-button>
            </a-space>
          </div>
        </div>
      </div>
    </template>
  </PageMain>
  <a-modal
    v-model:visible="removePopKey"
    title-align="start"
    class="chunk-delete-box"
    width="448px"
  >
    <template #title>
      <span style="font-size: 16px; font-weight: bold; color: #394d73">是否确认删除该项目</span>
    </template>
    <div class="chunk-delete-info-box" style="font-size: 14px; font-weight: normal; color: #465a80">
      <icon-exclamation-circle-fill class="text-yellow-500" />
      删除后该项目无法恢复
    </div>
    <template #footer>
      <div class="w-full h-full flex justify-end items-center">
        <a-button @click="removePopKey = false">取消</a-button>
        <a-button type="primary" class="ml-2" @click="deleteClick">确定</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue';
import { addTableData, Rules, CreateColumnData } from './values';
import { useRouter, useRoute } from 'vue-router';
const loading = ref<boolean>(false);
import { deepClone } from '@/util/clonedeep';
import {
  getDetail,
  updateData,
  getAccountingSubject,
  getAccountingSubjectDetail,
  deleteCost,
  addCost,
  updateCost
} from '@/api/costManagement/voucher_management/index';
import { Message } from '@arco-design/web-vue';

const activeRow = ref(0);
const route = useRoute();
const AccountingSubjectArr = ref<any>([]);
const AccountingSubjectDetailArr = ref<any>([]);

// 删除资源
const removePopKey = ref<boolean>(false);
const removePopData = ref<any>(null);
const rowIndex = ref(0);
function deleteAsset(item: any, index: number) {
  removePopKey.value = true;
  removePopData.value = item;
  rowIndex.value = index;
}

/**
 * @method deleteClick 删除财务数据
 */
const deleteClick = async () => {
  const { id } = removePopData.value;
  try {
    if (id) {
      let res = await deleteCost(id);
      if (res.code == '00000') {
        // tableData.value.splice(index, 1);
        Message.success('删除成功');
      } else {
        Message.error(res.message);
      }
    } else {
      tableData.value.splice(rowIndex.value, 1);
    }
  } catch (err) {
    console.log(err);
  }
  await checkDetail();
  removePopKey.value = false;
};

// 表单数据
let handlerData = reactive<any>({
  credential_code: '',
  credential_name: ''
});
const router = useRouter();

const tableData = ref<any>([]);
/**
 * @method tableRowClick 表格点击事件
 */
function tableRowClick(row: any) {
  activeRow.value = row.index;
}

//获取会计科目
const getAccountingSubjectData = async () => {
  const { data, code } = await getAccountingSubject();
  if (code === '00000') {
    AccountingSubjectArr.value = data;
  }
};

/**
 * @method addRow 表格新增事件
 */
function addRow() {
  const index = tableData.value.length + 1;
  tableData.value.push({
    index,
    ...CreateColumnData(),
    isSave: false //保存
  });
  activeRow.value = index;
}

/**
 * @method editClick 表格编辑
 */
function editClick(item: any, index: number) {
  item.isSave = false;
  console.log(item, index, 'item');
}

/**
 * @method saveClick 表格编辑
 */
const saveClick = async (item: any) => {
  if (item.id) {
    //有id就是编辑更新
    const params = {
      accounting_subject: item.accounting_subject,
      accounting_subject_code: item.accounting_subject_code,
      accounting_subject_detail: item.accounting_subject_detail,
      amount: Number(item.amount),
      cost_accounting_subject_id: item.id,
      id: item.id,
      credential_id: route.query.id, //
      summary: item.summary
    };
    let res = await updateCost(params);
    if (res.code === '00000') {
      item.isSave = true;
      return checkDetail();
    } else {
      Message.error(`${res.message}`);
    }
  } else {
    const params = {
      accounting_subject: item.accounting_subject,
      accounting_subject_code: item.accounting_subject_code,
      accounting_subject_detail: item.accounting_subject_detail,
      amount: item.amount,
      credential_id: route.query.id,
      summary: item.summary
    };
    let res = await addCost(params);
    if (res.code === '00000') {
      item.isSave = true;
      return checkDetail();
    } else {
      Message.error(`${res.message}`);
    }
  }
};

/**
 * @method callBack 取消
 */
const callBack = () => {
  router.push({
    name: 'voucherManage'
  });
};

/**
 * @method onCompleteClick 完成
 */
const onCompleteClick = async () => {
  const data = deepClone(tableData.value);
  data.forEach((item: any) => {
    delete item.isSave;
    delete item.index;
  });
  const params = {
    credential_code: handlerData.credential_code,
    credential_name: handlerData.credential_name,
    id: route.query.id
  };
  let res = await updateData(params);
  if (res.code === '00000') {
    return router.push({
      name: 'voucherManage'
    });
  }
};

/**
 * @method  checkDetail 获取详情
 */
const checkDetail = async () => {
  //调接口放开
  const res = await getDetail(route.query.id as string);
  if (res.code) {
    handlerData = res.data;
    // handlerData.credential_code = res.data.credential_code;
    // handlerData.credential_name = res.data.credential_name;
    tableData.value = res.data.cost_allocation.map((item: any) => {
      item.isSave = true;
      return item;
    });
  }
};

/**
 * @method accountingSubjectChange 会计科目
 */
const accountingSubjectChange = (val: any) => {
  AccountingSubjectDetailArr.value = [];
  val.accounting_subject_detail = '';
  val.accounting_subject_code = AccountingSubjectArr.value.find(
    (item: any) => item.subject === val.accounting_subject
  )?.code;
  if (val.accounting_subject_code) {
    getAccountingSubjectDetail({ accounting_subject_code: val.accounting_subject_code }).then(
      (res: any) => {
        if (res.code === '00000') {
          AccountingSubjectDetailArr.value = res.data;
        }
      }
    );
  }
};

onMounted(() => {
  getAccountingSubjectData();
  checkDetail();
});
</script>

<style lang="less" scoped>
.MainBox {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
}
.TabPaneClass {
  padding: 0 30px;
}
.content {
  margin-bottom: 33px;
  font-size: 14px;
  color: #465a80;

  .icon {
    color: #a3b0cc;
    font-size: 14px;
    font-weight: normal;
  }
  .text {
    padding-left: 16px;
    color: #465a80;
    font-size: 14px;
    font-weight: normal;
  }
}
.footer {
  border-top: 1px solid #ebf0fa;
  width: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: flex-end;
  height: 50px;
  align-items: center;
}
.circle-point {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border-width: 2px;
}

.ckd-inner-form-box {
  .arco-row {
    .arco-form-item {
      width: 50%;
      margin-top: 6px;
      :deep(.arco-form-item-label-col) {
        width: 120px;
      }
    }
  }
}
.make-plane {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.add-button-box {
  background-color: #f0f4fa;
  font-size: 14px;
  font-weight: normal;
  color: #465a80;
  border: 1px dashed #d3dbeb;
  border-radius: 4px;
}
:deep(.input__seach .arco-select) {
  width: 100%;
}
.foot-class {
  height: 68px;
  background: #ffffff;
  position: fixed;
  left: 220px;
  bottom: 0;
  width: calc(100vw - 220px);
  color: white;
  text-align: center;
  padding: 10px;
  box-shadow: 0 0 6px 0 rgba(57, 77, 115, 0.1);
  display: flex;
  justify-content: flex-end;
}
</style>
